<template>
  <div class="payment-container">
    <!-- 支付标题 -->
    <h2 class="title">💰 订单支付</h2>

    <!-- 订单信息 -->
    <div class="payment-info">
      <p><strong>订单号：</strong>{{ orderNumber }}</p>
      <p><strong>应付金额：</strong><span class="amount">{{ orderAmount }} 元</span></p>
      <p><strong>下单时间：</strong>{{ formattedCreateTime }}</p>
      <p v-if="countdown > 0" class="countdown"><strong>剩余支付时间：</strong>{{ countdown }} 秒</p>
      <p v-else class="timeout"><strong>⚠️ 订单已超时</strong></p>
    </div>

    <!-- 支付按钮 -->
    <el-button type="primary" @click="handlePay" :disabled="isTimeout" class="pay-btn">
      立即支付
    </el-button>
  </div>
</template>


<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { payOrder } from '@/apis/orders.js'
import {ElMessage} from "element-plus";

const route = useRoute()
const router = useRouter()

// 接收参数
const orderNumber = ref('')
const orderAmount = ref(0)
const createTime = ref(null)
const countdown = ref(900) // 15 分钟 = 900 秒
let timer = null
const isTimeout = ref(false)

onMounted(() => {
  // 获取路由参数
  orderNumber.value = route.query.number
  orderAmount.value = parseFloat(route.query.amount)
  createTime.value = new Date(route.query.createTime)

  // 启动倒计时
  startCountdown()

  // 页面加载时检查是否已超时
  checkIfTimeout()
})

onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
})

// 格式化创建时间
const formattedCreateTime = ref('')

function formatTime(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 倒计时逻辑
function startCountdown() {
  formattedCreateTime.value = formatTime(createTime.value)

  timer = setInterval(() => {
    const now = new Date()
    const diff = Math.floor((now - createTime.value) / 1000)
    const remaining = 900 - diff

    if (remaining <= 0) {
      isTimeout.value = true
      clearInterval(timer)
      setTimeout(() => {
        ElMessage.warning('订单已超时，即将返回首页')
        router.push('/')
      }, 1000)
    } else {
      countdown.value = remaining
    }
  }, 1000)
}

// 检查是否已超时（用户刷新页面也能检测）
function checkIfTimeout() {
  const now = new Date()
  const diff = Math.floor((now - createTime.value) / 1000)
  if (diff >= 900) {
    isTimeout.value = true
    ElMessage.warning('订单已超时，请重新下单')
    setTimeout(() => {
      router.push('/')
    }, 2000)
  }
}

// 支付按钮点击
const handlePay = async () => {
  if (isTimeout.value) {
    ElMessage.warning('订单已超时，请重新下单')
    return
  }

  try {
    const res = await payOrder(orderNumber.value)
    if (res.code === 0) {
      ElMessage.success('支付成功！')
      router.push({
        path: '/order/success',
        query: {
          number: orderNumber.value,
          amount: orderAmount.value,
        },
      }) // 支付成功页
    } else {
      ElMessage.error(res.message || '支付失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付请求失败')
  }
}
</script>

<style scoped lang="scss">
$primary-color: #d4a373;
$light-gray: #f5f5f5;
$dark-text: #333;

.payment-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 40px 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 24px rgba(0, 0, 0, 0.08);
  text-align: center;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.title {
  font-size: 28px;
  color: $dark-text;
  margin-bottom: 20px;
  letter-spacing: 1px;
}

.payment-info {
  background: #f9f9f9;
  padding: 25px;
  border-radius: 10px;
  margin-bottom: 30px;
  text-align: left;
  line-height: 1.8;
  border-left: 4px solid $primary-color;
}

.payment-info p {
  margin: 8px 0;
  color: #444;
}

.amount {
  color: $primary-color;
  font-size: 20px;
  font-weight: bold;
}

.countdown {
  color: #666;
}

.timeout {
  color: red;
  font-weight: bold;
}

.pay-btn {
  width: 100%;
  background: linear-gradient(to right, lighten($primary-color, 6%), darken($primary-color, 6%));
  color: white;
  font-size: 16px;
  font-weight: 500;
  border: none;
  border-radius: 6px;
  padding: 14px 20px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba($primary-color, 0.2);
  }

  &:active {
    transform: scale(0.98);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}
</style>

